package com.tenghui.assisting.controller;

import java.util.List;

import com.tenghui.common.enums.AuthStatus;
import com.tenghui.system.service.ISysUserService;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.tenghui.common.annotation.Log;
import com.tenghui.common.core.controller.BaseController;
import com.tenghui.common.core.domain.AjaxResult;
import com.tenghui.common.enums.BusinessType;
import java.io.InputStream;
import java.util.Map;

import org.springframework.web.multipart.MultipartFile;
import com.tenghui.assisting.domain.Farmers;
import com.tenghui.assisting.service.IFarmersService;
import com.tenghui.common.utils.poi.ExcelUtil;
import com.tenghui.common.core.page.TableDataInfo;

import static com.tenghui.common.core.domain.AjaxResult.error;

/**
 * 农户Controller
 *
 * @author tenghui
 * @date 2025-10-04
 */
@RestController
@RequestMapping("/assisting/farmers")
public class FarmersController extends BaseController {
    @Autowired
    private IFarmersService farmersService;

    @Autowired
    private ISysUserService sysUserService;

    @Value("${tenghui.farmers}")
    private Long farmersRoleId;
    /**
     * 查询农户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Farmers farmers) {
        startPage();
        List<Farmers> list = farmersService.selectFarmersList(farmers);
        return getDataTable(list);
    }

    /**
     * 导出农户列表
     */
    @Log(title = "农户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Farmers farmers) {
        List<Farmers> list = farmersService.selectFarmersList(farmers);
        ExcelUtil<Farmers> util = new ExcelUtil<Farmers>(Farmers.class);
        util.exportExcel(response, list, "农户数据");
    }

    /**
     * 下载模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<Farmers> util = new ExcelUtil<Farmers>(Farmers.class);
        util.importTemplateExcel(response, "农户数据");
    }

    /**
     * 导入数据
     */
    @Log(title = "农户", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<Farmers> util = new ExcelUtil<Farmers>(Farmers.class);
        InputStream inputStream = file.getInputStream();
        List<Farmers> list = util.importExcel(inputStream);
        inputStream.close();
        int count = farmersService.batchInsertFarmers(list);
        return AjaxResult.success("导入成功" + count + "条信息！");
    }

    /**
     * 获取农户详细信息
     */
    @GetMapping(value = "/{farmersId}")
    public AjaxResult getInfo(@PathVariable("farmersId") String farmersId) {
        return success(farmersService.selectFarmersByFarmersId(farmersId));
    }

    /**
     * 新增农户
     */
    @Log(title = "农户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Farmers farmers) {
        return toAjax(farmersService.insertFarmers(farmers));
    }

    /**
     * 修改农户
     */
    @Log(title = "农户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Farmers farmers) {
        return toAjax(farmersService.updateFarmers(farmers));
    }

    /**
     * 删除农户
     */
    @Log(title = "农户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{farmersIds}")
    public AjaxResult remove(@PathVariable String[] farmersIds) {
        return toAjax(farmersService.deleteFarmersByFarmersIds(farmersIds));
    }

    /*
     * 查询用户的农户认证信息
     * 返回 审核状态 + 拒绝理由
     */
    @GetMapping("/getAuthStatusInfo")
    public AjaxResult getAuthStatusInfo() {
        Map<String,Object> authStatusInfo = farmersService.getAuthStatusInfo();
        return success(authStatusInfo);
    }

    /*
     * 重新认证按钮 更新拒绝状态
     */
    @PutMapping("/updateAuthRejectInfo")
    public AjaxResult updateAuthRejectInfo(@RequestBody Farmers farmers) {
        return toAjax(farmersService.updateAuthRejectInfo(farmers));
    }

    /**
     * 通过认证
     */
    @Log(title = "通过认证", businessType = BusinessType.UPDATE)
    @PutMapping("/agree/{farmersId}")
    // 添加事务管理，确保两个操作（角色认证和认证状态更新）在一个事务中
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult agree(@PathVariable String farmersId) {
        // 参数校验 判断它一定有非空值
        if(StringUtils.isBlank(farmersId)) return error("农户ID不能为空");
        try{
            // 查询农户的信息
            Farmers farmers = farmersService.selectFarmersByFarmersId(farmersId);
            if(farmers == null) return  error("农户信息不存在");
            // 获取该农户的用户ID
            Long userId = farmers.getUserId();
            if(userId == null ) return error("用户ID不存在");
            // 通过认证 --- 更新该用户角色为农户
            sysUserService.insertUserAuth(userId,new Long[] {farmersRoleId});
            // 更新认证状态
            Farmers updateFarmers = new Farmers();
            updateFarmers.setFarmersId(farmersId);
            updateFarmers.setAuthStatus(AuthStatus.APPROVED.getCode());
            int result = farmersService.updateFarmers(updateFarmers);
            return toAjax(result);

        }catch (Exception e){
            return error("农户认证通过失败");
        }
    }

    /*
     * 拒绝认证
     */
    @Log(title = "农户", businessType = BusinessType.UPDATE)
    @PutMapping("/reject/{farmersId}")
    // 添加事务管理，确保两个操作（角色认证和认证状态更新）在一个事务中
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult reject(@PathVariable String farmersId, @RequestBody String rejectReason) {
        // 参数校验 判断一定有非空值
        if (StringUtils.isBlank(farmersId)) return error("农户ID不能为空");
        if (StringUtils.isBlank(rejectReason)) return error("拒绝原因不能为空");
        System.out.println(rejectReason);
        try {
            // 查询农户的信息
            Farmers farmers = farmersService.selectFarmersByFarmersId(farmersId);
            if (farmers == null) return error("农户信息不存在");
            // 更新认证状态
            Farmers updateFarmers = new Farmers();
            updateFarmers.setFarmersId(farmersId);
            updateFarmers.setRejectReason(rejectReason);
            updateFarmers.setAuthStatus(AuthStatus.REJECTED.getCode());
            int result = farmersService.updateFarmers(updateFarmers);
            return toAjax(result);
        } catch (Exception e) {
            return error("农户认证拒绝失败");
        }
    }
}
